$(() => {
  if (location.href === 'https://www.jd.com/?d') {
    window.history.back(-1)
  }

  // 监听消息传递
  chrome.extension.onMessage.addListener(
    function (req, sender, res) {
      if(req.action === 'completed'){
        console.log(req.url)
        //页面加载完毕
        if(/^https:\/\/item\.jd\.com\/\d+\.html/.test(req.url)){
          setTimeout(function () {
            window.scrollTo(0, document.body.scrollHeight)
            setTimeout(function () {
              getDetail(req)
            }, 2000)
          }, 1000)
        }else if(/^https:\/\/[a-z0-9A-Z_]+\.jd\.com\/(advance|view)_search-/.test(req.url)){
          window.scrollTo(0, document.body.scrollHeight)
          setTimeout(function () {
            getList(req, res)
          }, 500)
        }
      }
      // 一定要 return
      return true
    }
  )
})

// 获取商品列表以及sku
function getList() {
  var list = $(".j-module[module-function*='saleAttent']>ul>li,#J_GoodsList > ul > li,div.jSearchList>.j-module>ul>li")

  console.log(`商品数量：${list.length}`)
  let  productList = []

  if (/^http[s]{0,1}:\/\/[a-zA_Z0-9_]+\.jd\.com.*/.test(location.href)  && list && list.length > 0) {
    // 排列数据
    list.each(function () {
      let info = new Object()
      // 京东一个sku 拥有独立的详情,所以直卖网这边就没有sku
      

      let scrollList = $(this).find('.jScroll ul>li')
      if (scrollList && scrollList.length > 0) {
        scrollList.each(function() {
          productList.push([{ url: $(this).attr('data-href'), id: 'jd_' + $(this).attr('sid') }])
          //skuList.push({ url: $(this).attr('data-href'), id: $(this).attr('sid') })
        })
      } else {
        let url = $(this).find('.jPic a').attr('href')
        let id = /\/\/item\.jd\.com\/(\d+)\.html/.exec(url)
        if(id){
          productList.push([{ url, id: 'jd_' + id[1]}])
        }
        
      }
      
    })
    // 判断分页组件是否为最后一个 是则开始爬取sku数据并上传 否则继续获取列表
    let endTxt = $('.jPage a[class=current] + span').text()
    let endTxt2 = $('.jPage a[class=jPageCurrent] + span').text()
    if (endTxt.indexOf('下一页') !== -1 || endTxt2.indexOf('下一页') !== -1) {
      sendMsg({ data: productList}, 'end')
    } else {
      //如果是脚本翻页
      if ($('.jPage .jPageCurrent + a').attr('href') === 'javascript:;') {
        sendMsg({ data: productList }, 'nextSamePage')
        setTimeout(() => {
          //获取当前页
          let page = $('.jPage .jPageCurrent').text()
          //下一页
          $('.jPage .jPageCurrent + a')[0].click()
          //如果下一页加载完，才去解析页面
          let timer = setInterval(()=>{
            if($('.jPage .jPageCurrent').text()!=page){
              clearInterval(timer)
              getList()
            }
          },1000)
        }, 1000)
      } else {
        //let nextPage = $('.jPage a[class=current] + a').attr('href')
        sendMsg({ data: productList,url:$('.jPage a[class=current] + a').attr('href')}, 'next')
        /*
        setTimeout(() => {
          window.location.href = $('.jPage a[class=current] + a').attr('href')
        }, 2000)
        */
      }
    }
  } else {
    console.log('not found')
   // alert("No data")
  }
}

// 获取sku数据
function getDetail(req) {
  var detailInfo = new Object()
  if (/^https:\/\/item.jd.com\/.+html/.test(location.href)) {
    let parameter = $('.parameter2 li')
    detailInfo.brand = $('#parameter-brand li:first-child').attr('title')
    detailInfo.productSourceInfo = getDetails()
    detailInfo.title = detailInfo.productSourceInfo.title
    let weight = ''
    parameter.each(function() {
      if ($(this).text().indexOf('商品毛重') !== -1) {
        weight = $(this).attr('title')
      }
    })
    if (weight.indexOf('kg') !== -1) {
      detailInfo.weight = weight.replace('kg', '')
    } else if (weight.indexOf('g') !== -1) {
      detailInfo.weight = parseFloat(weight.replace('g', '')) / 1000
    } else {
      detailInfo.weight = weight
    }
    detailInfo.specifications = new Array()
    detailInfo.images = getNoSkuDetailImages()
    var colorSkuNodes = req.hasSku ? $('#choose-attr-1 .dd .item') : []
    var sizeSkuNodes = req.hasSku ? $('#choose-attr-2 .dd .item') : []
    
    var colorSelected = req.hasSku ? $('#choose-attr-1 .dd .item.selected').attr('data-value') : []
    var sizeSelected = req.hasSku ? $('#choose-attr-2 .dd .item.selected').attr('data-value') : []
    
    if (colorSkuNodes.length > 0) {
      let values = getSpecifications(colorSkuNodes)
      detailInfo.specifications = detailInfo.specifications.concat({
        name: '颜色',
        values: values
      })
    }
    if (sizeSkuNodes.length > 0) {
      let values = getSpecifications(sizeSkuNodes)
      detailInfo.specifications = detailInfo.specifications.concat({
        name: '规格',
        values: values
      })
    }
    detailInfo.productSpecifications = {
      distributionAmount: 0,
      // 价格有时会出现定金 只用.summary-price .p-price>.price 会将定金和价格拼接到一起 上传时会出现金额格式错误
      sellingPrice: $('.summary-price .p-price.ys-price>.price').text() ? $('.summary-price .p-price.ys-price>.price').text() : $('.summary-price .p-price>.price').text(),
      value: '',
      names: [],
      name0: colorSelected
    }
    let SpecificationsValue = new Array()
    detailInfo.productSpecifications.names = new Array()
    if (colorSelected) {
      detailInfo.productSourceInfo.name += ` ${colorSelected} `
      SpecificationsValue.push(colorSelected)
      detailInfo.productSpecifications.names.push(colorSelected)
    }
    if (sizeSelected) {
      detailInfo.productSourceInfo.name += ` ${sizeSelected} `
      SpecificationsValue.push(sizeSelected)
      detailInfo.productSpecifications.names.push(sizeSelected)
      detailInfo.productSpecifications.name1 = sizeSelected
    }
    detailInfo.productSpecifications.value = SpecificationsValue.join(',')
    detailInfo.productSourceType = '2'
    if($('#J-detail-content .loading-style1').length === 0 && $('#J-detail-content img[data-lazyload]').length === 0){
      detailInfo.info = getContent()
      sendMsg(detailInfo, 'upload')
    }else{
      var timer = setInterval(function() {
        if ($('#J-detail-content .loading-style1').length === 0 && !$('#J-detail-content img').attr('data-lazyload')) {
          detailInfo.info = getContent()
          sendMsg(detailInfo, 'upload')
          clearInterval(timer)
        }
      }, 1000)
    }
  }
}

function getContent(){
  let cont = $('#J-detail-content')
  if(cont.find('a[target="_blank"]').length > 0){
    cont.find('a[target="_blank"]').eq(0).parents('.ssd-module').remove()
  }
  return cont.html()
}

// 获取商品介绍图片
function getDetailsImages() {
  const formwork = $('#J-detail-content img')
  let detailImages = new Array()
  formwork.each(function() {
    detailImages.push($(this).attr('src'))
  })
  return detailImages
}

// 无sku时 将商品详情图组作为商品主图
function getNoSkuDetailImages() {
  var imageNodes = $('#spec-list li')
  var imageList = new Array()
  if (imageNodes && imageNodes.length > 0) {
    imageNodes.length > 5 ? imageNodes = imageNodes.slice(0, 5) : null
    imageNodes.each(function(i) {
      let isMain 
      i === 0 ? isMain = true : isMain = false
      imageList.push({ imageURL: $(this).find('img').attr('src').replace(/\/n[0-9]{1}\//, '/n1/'), isMain: isMain , sort: i, streamMediaType: 'IMG' })
    })
  }
  return imageList
}

// 获取商品价格/库存/名称等规格
function getSpecifications(node) {
  let values = new Array()
  node.each(function() {
    if ($(this).attr('title').indexOf('无货') === -1) {
      values.push({
        icon: '',
        value: $(this).attr('data-value')
      })
    }
  })
  return values
}

// 获取商品介绍/规格详情
function getDetails() {
  let details = new Array()
  let clearfixArr = new Array()
  let parameter = $('.parameter2 li')
  let parameterList = new Array()
  if ($('.Ptable-item') && $('.Ptable-item').length > 0) {
    $('.Ptable-item').each(function() {
      let clearfix = $(this).find('.clearfix')
      clearfix.each(function() {
        clearfixArr.push({ title: $(this).find('dt').text(), value: $(this).find('dd').text() })
      })
      details.push({
        text: $(this).find('h3').text(),
        data: clearfixArr
      })
    })
  }
  if (parameter && parameter.length > 0) {
    parameter.each(function() {
      parameterList.push($(this).text())
    })
  }
  var colorSelected = $('#choose-attr-1 .dd .item.selected').attr('data-value') || ''
  var sizeSelected = $('#choose-attr-2 .dd .item.selected').attr('data-value') || ''
  return {
    url:location.href,
    title: $('.sku-name').text().trim(),
    name: colorSelected ? colorSelected + sizeSelected : '商品信息',
    props: parameterList,
    specs: details
  }
}

// 将获取内容传递给后台脚本进行处理
function sendMsg(msg, cmd) {
　　chrome.extension.sendMessage({ 'msg': msg, 'cmd': cmd })
}
